#include "util.h"


int funcA()
{
	return 1;
}

string mapname[100] = {"CREATE","DROP","SELECT","DELETE","INSERT","UPDATE","=","<>","<",">",">=","<=","like","and","or","atom","int","char","varchar"};

string getSymbol(int code)
{
	return mapname[code];
}

int getNextAcIndex(string src,int curIndex)
{
	int returnIndex = curIndex;
	while(src.at(returnIndex)==' '|| src.at(returnIndex)=='\t')
	{
		if(returnIndex >= src.length())
		{
			returnIndex = -1;
			break;
		}
		returnIndex++;
	}
	return returnIndex;
}

int getOPfromEquation(string sentence)
{
	if(sentence.find(">=")!=-1)
	{
		return OP::NOT_LESS;
	}
	if(sentence.find("<=")!=-1)
	{
		return OP::NOT_LARGE;
	}
	if(sentence.find("<>")!=-1)
	{
		return OP::NOT_EQUL;
	}
	if(sentence.find(">")!=-1)
	{
		return OP::LARGE;
	}
	if(sentence.find("<")!=-1)
	{
		return OP::LESS;
	}
	if(sentence.find("=")!=-1)
	{
		return OP::EQUL;
	}
	string tmp = to_upper_copy(sentence);
	if(tmp.find("LIKE")!=-1)
	{
		return OP::LIKE;
	}
	if(tmp.find("IS")!=-1)
	{
		return OP::EQUL;
	}
	return OP::EQUL;
}

void printTree(tree* pRoot,int depth)
{
	if(pRoot==NULL)
	{
		return;
	}
	printTree(pRoot->left,depth+2);
	for(int i = 0;i<depth;i++)
	{
		cout<<" ";
	}
	if(pRoot->code == LOGIC::ATOM)
	{
		cout<<pRoot->cond.dstValue<<" "<<getSymbol(pRoot->cond.op)<<" "<<pRoot->cond.srcValue<<endl;
	}else
	{
		cout<<getSymbol(pRoot->code)<<endl;
	}

	printTree(pRoot->right,depth+2);
}

string&   replace_all(string&   str,const   string&   old_value,const   string&   new_value)   
{   
	while(true)   {   
		string::size_type   pos(0);   
		if(   (pos=str.find(old_value))!=string::npos   )   
			str.replace(pos,old_value.length(),new_value);   
		else   break;   
	}   
	return   str;   
}   

void setBit(char* buffer, int pos, bool bit)
{
	int numOfByte = pos / 8, numOfBit = pos % 8;
	if (bit)
		buffer[numOfByte] |= (0x80 >> numOfBit);
	else
		buffer[numOfByte] &= (~(0x80 >> numOfBit));

}

bool getBit(const char* buffer, int pos)
{
	int numOfByte = pos / 8, numOfBit = pos % 8;
	if ((buffer[numOfByte] & (0x80 >> numOfBit)) == 0)
		return false;
	else
		return true;
}

void cleanTree(ParsedTree* tree)
{
	if (tree == NULL)
		return;
	cleanTree(tree->left);
	cleanTree(tree->right);
	delete tree;
}

void split(string str, char token, vector<string>* resultList, bool trim)
{
	int pre_index = 0, index = 0, len = 0;	
	while ((index = str.find_first_of(token, pre_index)) >= 0)
	{
		if ((len = index - pre_index) != 0)
			resultList->push_back(str.substr(pre_index, len));
		else if (!trim)
			resultList->push_back("");
		pre_index = index + 1;
	}
	string endstr = str.substr(pre_index);
	if (!trim)
		resultList->push_back(endstr.empty() ? "" : endstr);
	else if (!endstr.empty())
		resultList->push_back(endstr);
}
